<template>
  <el-card shadow="never" class="border-0">
    <Search @search="getData" @reset="resetSearchForm" :model="searchForm">
      <search-item label="关键词" prop="keyword">
        <el-input v-model="searchForm.keyword" placeholder="手机号/邮箱/会员昵称" clearable />
      </search-item>

      <template #show>
        <search-item label="会员等级" prop="user_level_id">
          <el-select v-model="searchForm.user_level_id" placeholder="请选择会员等级">
            <el-option v-for="item in user_level" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </search-item>
      </template>
    </Search>

    <list-header @create="handleCreate" @refresh="getData" />

    <el-table :data="tableData" stripe style="width: 100%" v-loading="loading">
      <el-table-column label="会员" width="200">
        <template #default="{ row }">
          <div class="flex items-center">
            <!-- 如果获取不到row.avatar，就会使用内部的img -->
            <el-avatar :size="40" :src="row.avatar" @error="() => true">
              <img
                src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png"
              />
            </el-avatar>
            <div class="ml-3">
              <h6>{{ row.username }}</h6>
              <small>{{ row.id }}</small>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="会员等级" align="center">
        <template #default="{ row }">
          {{ row.user_level?.name || '-' }}
        </template>
      </el-table-column>
      <el-table-column label="登录注册" align="center" width="250">
        <template #default="{ row }">
          <div class="text-sm">注册时间 : {{row.create_time}}</div>
          <div class="text-sm" v-if="row.last_login_time">最后登录 : {{row.last_login_time}}</div>
        </template>
      </el-table-column>
      <el-table-column label="状态" width="100">
        <template #default="{ row }">
          <el-switch
            :disabled="row.super === 1"
            :model-value="row.status"
            :active-value="1"
            :inactive-value="0"
            :loading="row.statusLoading"
            @change="handleStatusChange($event, row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <small class="text-sm text-gray-500" v-if="scope.row.super === 1">
            暂无操作
          </small>

          <div v-else>
            <el-button
              type="primary"
              size="small"
              text
              @click="handleEdit(scope.row)"
            >
              修改
            </el-button>
            <el-popconfirm
              title="是否要删除该管理员？ "
              confirmButtonText="确认"
              cancelButtonText="取消"
              @confirm="handleDelete(scope.row.id)"
            >
              <template #reference>
                <el-button type="primary" size="small" text> 删除 </el-button>
              </template>
            </el-popconfirm>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <div class="flex items-center justify-center mt-5">
      <el-pagination background layout="prev, pager, next" :total="total" :current-page="currentPage"
        :page-size="limit" @current-change="getData"/>
    </div>

    <FormDrawer ref="formDrawerRef" :title="drawerTitle" @submit="handleSumbit" @cancel="handleCancel">
      <el-form :model="form" ref="formRef" :rules="rules" label-width="100px" :inline="false">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名" />
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" placeholder="请输入密码" type="password" show-password/>
        </el-form-item>

        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="form.nickname" placeholder="请输入昵称"/>
        </el-form-item>

        <el-form-item label="头像" prop="avatar" ref="chooseImageUploadRef">
          <choose-image v-model="form.avatar" @upImgSuc="handleUpImgSuc" />
        </el-form-item>

        <el-form-item label="会员等级" prop="user_level_id">
          <el-select v-model="form.user_level_id" placeholder="请选择会员等级">
            <el-option v-for="item in user_level" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="手机" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机"/>
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱"/>
        </el-form-item>

        <el-form-item label="状态">
          <el-switch v-model="form.status" :active-value="1" :inactive-value="0"/>
        </el-form-item>
      </el-form>
    </FormDrawer>
  </el-card>
</template>

<script setup>
  import { ref } from 'vue'
  import {
    getUserListApi,
    updateUserApi,
    createUserApi,
    updateUserStatusApi,
    deleteUserApi
  } from '@/api/user.js'

  import FormDrawer from '@/components/FormDrawer.vue'
  import ChooseImage from '@/components/ChooseImage.vue'
  import ListHeader from '@/components/ListHeader.vue'
  import Search from '@/components/Search.vue'
  import SearchItem from '@/components/SearchItem.vue'
  import { useInitTable, useInitForm } from '@/hooks/useCommon.js'

  // 角色列表
  const user_level = ref([])
  const {
    searchForm,
    resetSearchForm,
    tableData,
    loading,
    currentPage,
    total,
    limit,
    getData,
    handleDelete,
    handleStatusChange,
  } = useInitTable({
    // 搜索需要的参数
    searchForm: {
      keyword: '',
      user_level_id: null
    },
    // 获取表单的api
    getlist: getUserListApi,
    delete: deleteUserApi,
    updateStatus: updateUserStatusApi,
    // 获取表单成功的回调
    onGetListSuccess: (res) => {
      tableData.value = res.list.map((o) => {
        o.statusLoading = false
        return o
      })
      total.value = res.totalCount
      user_level.value = res.user_level
    },
  })

  const {
    formDrawerRef,
    formRef,
    form,
    rules,
    drawerTitle,
    handleCreate,
    handleEdit,
    handleSumbit,
    handleCancel,
  } = useInitForm({
    form: {
      username: '',
      password: '',
      nickname: '',
      phone: '',
      email: '',
      user_level_id: null,
      status: 1,
      avatar: '',
    },
    rules: {
      username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
      password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
      role_id: [
        { required: true, message: '请选择所属管理员', trigger: 'change' },
      ],
      avatar: [{ required: true, message: '请上传图片', trigger: 'change' }],
    },
    getData,
    create: createUserApi,
    update: updateUserApi,
  })

  // 上传图片成功
  const chooseImageUploadRef = ref(null)
  function handleUpImgSuc() {
    chooseImageUploadRef.value.clearValidate()
  }
</script>

<style scoped>
  .avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }

  .avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
  }

  .el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
  }
</style>
